/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package expenseslist;

import java.sql.*;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

/**
 *
 * @author trunghpb
 */
public class DbAdapter {

    public DbAdapter() {
        fieldList = new LinkedList<FieldType>();
    }
    
    public Object[][] getArray(ResultSet rs) throws SQLException{
        
        _data = new Object[MySqlDb.getRowCount(rs)][fieldList.size()];
        int i = 0, j = 0;
        while (rs.next()){
            ListIterator<FieldType> fieldIter = (ListIterator<FieldType>) fieldList.iterator();
            j = 0;
            while (fieldIter.hasNext()){
                FieldType field = fieldIter.next();
                switch (field.fieldType){
                    case TYPE_INT:{
                        _data[i][j] = rs.getInt(field.fieldName);
                        break;
                    }
                    case TYPE_DOUBLE:{
                        _data[i][j] = rs.getDouble(field.fieldName);
                        break;
                    }
                    case TYPE_STRING:{
                        _data[i][j] = rs.getString(field.fieldName);
                        break;
                    }
                    case TYPE_DATE:{
                        _data[i][j] = rs.getDate(field.fieldName);
                        break;
                    }
                }
                j++;
            }
            i++;
        }
        return _data;
    }
    
    public void addInt(String fieldName){
        fieldList.add(new FieldType(fieldName, TYPE_INT));
    }
    
    public void addDate(String fieldName){
        fieldList.add(new FieldType(fieldName, TYPE_DATE));
    }
    
    public void addDouble(String fieldName){
        fieldList.add(new FieldType(fieldName, TYPE_DOUBLE));
    }
    
    public void addString(String fieldName){
        fieldList.add(new FieldType(fieldName, TYPE_STRING));
    }
    
    class FieldType{
        public String fieldName;
        public int fieldType;

        public FieldType(String name, int type) {
            fieldName = name;
            fieldType = type;
        }
        
    }
    
    private List<FieldType> fieldList;
    
    private Object[][] _data;
    
    private static final int TYPE_INT = 0;
    private static final int TYPE_DOUBLE = 1;
    private static final int TYPE_STRING = 2;
    private static final int TYPE_DATE = 3;   
    
}
